<template>
  <div>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="活动名称" prop="loginName">
        <el-input v-model="ruleForm.loginName" />
      </el-form-item>
      <el-form-item label="活动区域" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item label="活动区域" prop="code">
        <el-input v-model="ruleForm.code" />
        <img :src="img" @click="getImg">
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        loginName: 'demo',
        password: '888itcast.CN764%...',
        code: '',
        loginType: 0,
        clientToken: ''
      },
      rules: {
        loginName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    img() {
      return `https://likede2-java.itheima.net/api/user-service/user/imageCode/${this.ruleForm.clientToken}`
    }
  },
  created() {
    this.getImg()
  },
  methods: {
    async submitForm() {
      await this.$refs.ruleForm.validate()
      await this.$store.dispatch('user/loginUser', this.ruleForm)
      this.$router.push('/')
    },

    randChar(length, characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
      // length为所需长度，characters为所包含的所有字符，默认为字母+数字。
      characters = characters.split('')// 分割字符。
      let result = ''// 返回的结果。
      while (result.length < length) result += characters[Math.round(Math.random() * characters.length)]
      return result
    },
    getImg() {
      this.ruleForm.clientToken = this.randChar(32)
    }

  }
}
</script>

<style scoped lang="scss">

</style>
